#!/home/catmd5/.venv/bin/python3.8
import warnings

warnings.filterwarnings(action='ignore', module='.*paramiko.*')

import json

import paramiko
import socket
from concurrent.futures import ThreadPoolExecutor
from cmd_line import Server

with open("./md5_config.json", 'r', encoding='utf-8') as fr:
    node_lists = json.load(fr)
ip_range = node_lists['ip_range']
VERSION = node_lists.get('version', "None")


def update(ip):
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        socket.setdefaulttimeout(1)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((ip, 22))
        s.send(bytes("INFO\r\n", 'UTF-8'))
        result = s.recv(1024).decode()
        line = Server(ip, 22, "muyi", "muyi@123")
        line.connect()
        line.open_ssh()
        mes = line.ssh_send_cmd('docker ps -q --filter "name=mooe-core"')
        if mes:
            data = line.ssh_send_cmd('ls /mooe/maps/unuse_cross_stopped.txt')
            if data:
                print(ip + "-docker", "error")
                line.ssh_send_cmd('rm -rf /mooe/maps/unuse_cross_stopped.txt')
            else:
                print(ip + "-docker", "ok")
        else:
            data = line.ssh_send_cmd('ls /opt/ros/maps/unuse_cross_stopped.txt')
            if data:
                print(ip, "error")
                line.ssh_send_cmd('rm -rf /opt/ros/maps/unuse_cross_stopped.txt')
            else:
                print(ip, "ok")
    except:
        pass
    finally:
        if line:
            line.close()
            del line


print("versions: %s" % VERSION)
if len(ip_range) != 2:
    ip_range = [2, 250]
with ThreadPoolExecutor(500) as pool:
    results = []
    robot_ip = node_lists["robot_ip"]
    for i in range(ip_range[0], ip_range[1] + 1):
        ip = robot_ip + str(i)
        results.append(pool.submit(update, ip))
